package com.jtjrenren.android.taxi.driver.manger.api;

import com.jtjrenren.android.taxi.driver.bean.api.ApiCommonT;
import com.jtjrenren.android.taxi.driver.bean.api.Token;
import com.jtjrenren.android.taxi.driver.manger.AppManger;
import com.jtjrenren.android.taxi.driver.utils.CustomeException;
import com.jtjrenren.android.taxi.driver.utils.ModuleUtils;
import com.library.utils.LogUtil;
import com.library.utils.StringUtils;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2016/8/29.
 */

public class PushWorks {
    public static final String SERVER_URL = "http://api.i952169.com.cn:8062";
    private static PushService pushService = creatClient().create(PushService.class);

    public static void getToken(String account, String apptype, String appVersion, final ApiWorks.ResponseListener<Token> listener) {
        LogUtil.log("token", "联网获取token()");
        pushService.getToken(account, apptype, appVersion)
                .subscribeOn(Schedulers.io())
                .map(new Func1<String, Token>() {
                    @Override
                    public Token call(String result) {
                        Token obj = null;
                        if (!StringUtils.isEmpty(result)) {
                            ApiCommonT commonApi = ModuleUtils.getCommonApi(result, Token.class);
                            if (commonApi.getCode() == 1 && commonApi.getData() != null) {
                                List<Token> list = commonApi.getData();
                                if (list.size() > 0)
                                    obj = list.get(0);
                            }
                        }
                        return obj;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Token>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        if (listener != null)
                            listener.onResponse(null);
                        LogUtil.log("token", "获取token报错！;" + e.toString());
                        CustomeException.handException(e);
                    }

                    @Override
                    public void onNext(Token apiDriverSr) {
                        if (listener != null)
                            listener.onResponse(apiDriverSr);
                        LogUtil.log("token", "联网获取token,结果：" + apiDriverSr.toString());
                    }
                });
    }

    public static void bindGtID(String gtid, final ApiWorks.ResponseListener<ApiCommonT> listener) {
        LogUtil.log("token", "bindGtID（）联网绑定gt");
        pushService.bindGtCID(gtid)
                .subscribeOn(Schedulers.io())
                .map(new Func1<String, ApiCommonT>() {
                    @Override
                    public ApiCommonT call(String result) {
                        ApiCommonT commonApi = null;
                        if (!StringUtils.isEmpty(result)) {
                            commonApi = ModuleUtils.getCommonApi(result, String.class);
                        }
                        return commonApi;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ApiCommonT>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        if (listener != null)
                            listener.onResponse(null);
                        CustomeException.handException(e);
                    }

                    @Override
                    public void onNext(ApiCommonT apiDriverSr) {
                        if (listener != null)
                            listener.onResponse(apiDriverSr);
                    }
                });
    }

    public static void pushMsg(String msg, ApiWorks.ResponseListener<String> listener) {
        LogUtil.log("push", "向服务器发送消息：" + msg);
        Observable<String> stringObservable = pushService.pushMsg(msg);
        setSubscribe(stringObservable, new Observer<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                LogUtil.log("push", "向服务器发送消息==> error:" + e.toString());
            }

            @Override
            public void onNext(String s) {
                LogUtil.log("push", "向服务器发送消息==>"+s);
                ApiCommonT<String> apiCommonT = ModuleUtils.getCommonApi(s, String.class);
                if (apiCommonT != null)
                    ModuleUtils.handCommon(apiCommonT.getCode());
            }
        });
    }

    public static void upLog(String log) {
        LogUtil.log("applog", "uplog:" + log);
        Observable<String> stringObservable = pushService.upLog(log);
        setSubscribe(stringObservable, new Observer<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(String s) {

            }
        });
    }

    private static <T> void setSubscribe(Observable<T> observable, Observer<T> observer) {
        observable.subscribeOn(Schedulers.io())
                .subscribeOn(Schedulers.newThread())//子线程访问网络
                .observeOn(AndroidSchedulers.mainThread())//回调到主线程
                .subscribe(observer);
    }

    public static Retrofit creatClient() {
        return new Retrofit.Builder()
                .baseUrl(SERVER_URL)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(new OkHttpClient.Builder()
                        .connectTimeout(10, TimeUnit.SECONDS)
                        .writeTimeout(30, TimeUnit.SECONDS)
                        .readTimeout(30, TimeUnit.SECONDS)
                        .addInterceptor(new Interceptor() {
                            @Override
                            public Response intercept(Chain chain) throws IOException {
                                Request originalRequest = chain.request();
                                if (StringUtils.isEmpty(AppManger.getInstance().token)) {
                                    return chain.proceed(originalRequest);
                                }
                                Request authorised = originalRequest.newBuilder()
                                        .header("ita", AppManger.getInstance().token)
                                        .build();
                                return chain.proceed(authorised);
                            }

                        })
                        .build())
                .build();
    }
}
